package com.huarun.common;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.huarun.common.util.MyException;
import com.huarun.common.util.ResultCodeValue;

/**
 * @author hqy
 * @创建时间   2018-10-15 10:01
 * @Description 异常拦截器
 */

@ControllerAdvice
@ResponseBody
public class ExceptionController {

	private static Logger logger = LoggerFactory.getLogger(ExceptionController.class);

	/**
	 * 400 - Bad Request
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(MissingServletRequestParameterException.class)
	public ResponseMessage handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
		logger.error("缺少请求参数", e);
		return new ResponseMessage().failureMessage(ResultCodeValue.R_PARAM_ERROR, "缺少请求参数", null);
	}

	/**
	 * 400 - Bad Request
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(HttpMessageNotReadableException.class)
	public ResponseMessage handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
		logger.error("参数解析失败", e);
		return new ResponseMessage().failureMessage(ResultCodeValue.R_PARAM_ERROR, "could_not_read_json", null);
	}

	/**
	 * 400 - Bad Request
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public ResponseMessage handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
		logger.error("参数验证失败", e);
		BindingResult result = e.getBindingResult();
		FieldError error = result.getFieldError();
		String field = error.getField();
		String code = error.getDefaultMessage();
		String message = String.format("%s:%s", field, code);
		return new ResponseMessage().failureMessage(ResultCodeValue.R_PARAM_ERROR, message, null);
	}

	/**
	 * 400 - Bad Request
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(BindException.class)
	public ResponseMessage handleBindException(BindException e) {
		logger.error("参数绑定失败", e);
		BindingResult result = e.getBindingResult();
		FieldError error = result.getFieldError();
		String field = error.getField();
		String code = error.getDefaultMessage();
		String message = String.format("%s:%s", field, code);
		return new ResponseMessage().failureMessage(ResultCodeValue.R_PARAM_ERROR, message, null);
	}

	/**
	 * 400 - Bad Request
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(ConstraintViolationException.class)
	public ResponseMessage handleServiceException(ConstraintViolationException e) {
		logger.error("参数验证失败", e);
		Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
		ConstraintViolation<?> violation = violations.iterator().next();
		String message = violation.getMessage();
		return new ResponseMessage().failureMessage(ResultCodeValue.R_PARAM_ERROR, "parameter:" + message, null);
	}

	/**
	 * 400 - Bad Request
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(ValidationException.class)
	public ResponseMessage handleValidationException(ValidationException e) {
		logger.error("参数验证失败", e);
		return new ResponseMessage().failureMessage(ResultCodeValue.R_PARAM_ERROR, "validation_exception", null);
	}

	/**
	 * 405 - Method Not Allowed
	 */
	@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	public ResponseMessage handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
		logger.error("不支持当前请求方法", e);
		return new ResponseMessage().failureMessage(ResultCodeValue.R_NO_SUPPORT, "request_method_not_supported", null);
	}

	/**
	 * 415 - Unsupported Media Type
	 */
	@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
	@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
	public ResponseMessage handleHttpMediaTypeNotSupportedException(Exception e) {
		logger.error("不支持当前媒体类型", e);
		return new ResponseMessage().failureMessage(ResultCodeValue.R_NO_SUPPORT, "content_type_not_supported", null);
	}

	/**
	 * 500 - Internal Server Error
	 */
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	@ExceptionHandler(Exception.class)
	public ResponseMessage handleException(Exception e) {
		logger.error("通用异常", e);
		return new ResponseMessage().failureMessage(ResultCodeValue.R_SYSTEM_CODE_ERROR, e.getMessage(), null);
	}

	/**
	 * 操作数据库出现异常:名称重复，外键关联
	 */
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	@ExceptionHandler(DataIntegrityViolationException.class)
	public ResponseMessage handleException(DataIntegrityViolationException e) {
		logger.error("操作数据库出现异常:", e);
		return new ResponseMessage().failureMessage(ResultCodeValue.R_SYSTEM_CODE_ERROR, "操作数据库出现异常：字段重复、有外键关联等", null);
	}

	/**
	 * 拦截捕捉自定义异常 MyException.class
	 * @return
	 */
	@ResponseBody
	@ExceptionHandler(value = MyException.class)
	public ResponseMessage myExceptionHandler(MyException e) {
		logger.error("拦截捕捉自定义异常:", e);
		return new ResponseMessage().failureMessage(e.getErrorCode(), e.getMessage(), null);
	}

}
